using System.Collections;
using UnityEngine;

public class AudioManager : MonoBehaviour
{
    public static AudioManager Instance { get; private set; }
    [SerializeField] private float sfxMinimumDistance;
    [SerializeField] private AudioSource[] sfx;
    [SerializeField] private AudioSource[] bgm;
    public bool playingBgm;
    private int bgmIndex;
    private bool canPlaySfx;

    private void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
        sfx = transform.Find("Sfx").GetComponentsInChildren<AudioSource>();
        bgm = transform.Find("Bgm").GetComponentsInChildren<AudioSource>();
        Invoke(nameof(AllowSfx), 1f); // Allow SFX to play after a short delay
    }

    private void Update()
    {
        if (!playingBgm)
        {
            StopAllBgm();
        }
        else
        {
            if (!bgm[bgmIndex].isPlaying)
            {
                PlayBgm(bgmIndex);
            }
        }
    }

    public void PlaySfx(int index, Transform source)
    {
        // if (sfx[index].isPlaying)
        // {
        //     return;
        // }
        if (!canPlaySfx) return;
        if (source && Vector2.Distance(PlayerManager.Instance.Player.transform.position, source.position) > sfxMinimumDistance)
        {
            return; // Don't play SFX if the source is too far away
        }
        if (index < 0 || index >= sfx.Length)
            return;
        sfx[index].pitch = Random.Range(0.7f, 1.2f); // Randomize pitch slightly for variety
        sfx[index].Play();
    }

    public void StopSfx(int index)
    {
        if (index >= 0 && index < sfx.Length)
        {
            sfx[index].Stop();
        }
    }

    public void StopSfxWithFade(int index)
    {
        if (index >= 0 && index < sfx.Length)
        {
            StartCoroutine(DecreaseVolume(sfx[index]));
        }
    }

    private static IEnumerator DecreaseVolume(AudioSource source)
    {
        float defaultVolume = source.volume;
        while (source.volume > 0.0001f)
        {
            source.volume -= source.volume * Time.deltaTime / 1.5f; // Decrease volume over 2 seconds
            yield return null;
            if (!(source.volume <= 0.0001f))
                continue;
            source.Stop();
            source.volume = defaultVolume; // Reset volume to default after stopping
            yield break; // Exit the coroutine
        }
    }

    // public void PlayRandomBgm()
    // {
    //     bgmIndex = Random.Range(0, bgm.Length);
    //     PlayBgm(bgmIndex);
    // }

    private void PlayBgm(int index)
    {
        bgmIndex = index;
        StopAllBgm();
        bgm[bgmIndex].Play();
    }

    private void StopAllBgm()
    {
        foreach (var audioSource in bgm)
        {
            audioSource.Stop(); // Stop all BGM before playing a new one
        }
    }

    private void AllowSfx() => canPlaySfx = true;
}
